<?php


namespace app\partner\controller;

use app\common\controller\CommonService;
use think\Controller;
use think\Db;
use think\facade\Cache;
use think\facade\Validate;
use think\Request;

class SetUp extends Controller
{
    /**
     *合伙人资料
     * @param Request $request
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function getPartnerInfo(Request $request)
    {
        $partnerId = $request->partnerId;
        $data = Db::name('partner')
            ->alias('s')
            ->join('user_manage u', 'u.id = s.uid', 'LEFT')
            ->where('s.id', $partnerId)
            ->field('u.id,u.headimgurl,u.xingming,u.code,u.tel,u.sex,u.shengri,u.province,u.city,u.alipay_id,u.payee_name,s.withdraw_password,s.password')
            ->find();
        if (!empty($data['password'])){
            $data['check_pass'] = 1;
        } else {
            $data['check_pass'] = 0;
        }
        if (!empty($data['withdraw_password'])){
            $data['check_withdraw_pass'] = 1;
        } else {
            $data['check_withdraw_pass'] = 0;
        }
        if (!empty($data['alipay_id'])){
            $data['check_alipay_id'] = 1;
        } else {
            $data['check_alipay_id'] = 0;
        }
        return CommonService::success($data);
    }

    /**
     *合伙人资料修改
     * @param Request $request
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function PartnerEdit(Request $request)
    {
        $partnerId = $request->partnerId;
        $requestData = $request->post();
        $validate = Validate::make([
            'id|用户id' => 'require|number',
            'xingming|姓名' => 'require',
            'sex|性别' => 'require|number',
            'shengri|生日' => 'require',
            'province|省份' => 'require',
            'city|城市' => 'require',
        ]);
        if (!$validate->check($requestData)) {
            return CommonService::error($validate->getError());
        }
        if (!empty($requestData['id'])){
            $uid = Db::name('partner')->where('id',$partnerId)->field('uid')->find();
            if ($uid['uid'] != $requestData['id']){
                return CommonService::error(1);
            }
        } else {
            return CommonService::error(1);
        }
        $result = Db::name('user_manage')->where('id', $requestData['id'])->update([
            'xingming' => $requestData['xingming'],
            'sex' => $requestData['sex'],
            'shengri' => $requestData['shengri'],
            'province' => $requestData['province'],
            'city' => $requestData['city'],
            'payee_name' => $requestData['xingming'],
        ]);
        if ($result){
            return CommonService::success([],106);
        } else {
            return CommonService::error(0);
        }
    }

    /**
     *合伙人密码修改
     * @param Request $request
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function partnerPasswordEdit(Request $request)
    {
        $partnerId = $request->partnerId;
        $requestData = $request->post();
        $validate = Validate::make([
            'password|原密码' => 'require',
            'newPassword|新密码' => 'require',
            'newPasswordTwo|重复新密码' => 'require',
        ]);
        if (!$validate->check($requestData)) {
            return CommonService::error($validate->getError());
        }
        $data = Db::name('partner')
            ->where('id',$partnerId)
            ->find();
        if (empty($data)){
            return CommonService::error(1);
        }
        if (md5($requestData['password']) != $data['password']){
            return CommonService::error(2);
        }
        if ($requestData['newPassword'] != $requestData['newPasswordTwo']){
            return CommonService::error(105);
        }
        $result = Db::name('partner')->where('id', $partnerId)->update([
            'password' => md5($requestData['newPassword']),
        ]);
        if ($result){
            return CommonService::success([],106);
        } else {
            return CommonService::error(0);
        }
    }

    /**
     *验证合伙人旧手机号
     * @param Request $request
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function checkOldTel(Request $request)
    {
        $partnerId = $request->partnerId;
        $requestData = request()->post();
        $validate = Validate::make([
            'tel|手机号' => 'require|mobile',
            'code|验证码' => 'require',
        ]);
        if (!$validate->check($requestData)) {
            return CommonService::error($validate->getError());
        }
        $userId = Db::name('user_manage')->where('tel', $requestData['tel'])->find();
        $partner = Db::name('partner')->where('uid', $userId['id'])->find();
        if ($partner['id'] != $partnerId) {
            return CommonService::error(1);
        }
        if ($requestData['code'] != Cache::get('smsCode' . $requestData['tel'])) {
            return CommonService::error(5);
        }
        $data['payee_name'] = $userId['payee_name'];
        return CommonService::success($data, '验证通过！');
    }

    /**
     *验证合伙人新手机号并修改手机号
     * @param Request $request
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function checkNewTel(Request $request)
    {
        $partnerId = $request->partnerId;
        $requestData = request()->post();
        $validate = Validate::make([
            'tel|手机号' => 'require|mobile',
            'code|验证码' => 'require',
        ]);
        if (!$validate->check($requestData)) {
            return CommonService::error($validate->getError());
        }
        $uid = Db::name('partner')->where('id', $partnerId)->value('uid');
        $userInfo = Db::name('user_manage')->where('id', $uid)->find();
        if (!$userInfo){
            return CommonService::error(1);
        }
        if ($requestData['code'] != Cache::get('smsCode' . $requestData['tel'])) {
            return CommonService::error(5);
        }
        $result = Db::name('user_manage')->where('id', $userInfo['id'])->update([
            'tel' => $requestData['tel'],
        ]);
        if ($result){
            return CommonService::success([],106);
        } else {
            return CommonService::error(0);
        }
    }

    /**
     *验证支付宝并绑定支付宝号
     * @param Request $request
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function AlipayIdAdd(Request $request)
    {
        $partnerId = $request->partnerId;
        $requestData = request()->post();
        $validate = Validate::make([
            'alipay_id|支付宝账户' => 'require',
        ]);
        if (!$validate->check($requestData)){
            return CommonService::error($validate->getError());
        }
        $userId = Db::name('partner')->where('id', $partnerId)->value('uid');
        if (!$userId){
            return CommonService::error(1);
        }
        $result = Db::name('user_manage')->where('id', $userId)->update([
            'alipay_id' => $requestData['alipay_id'],
        ]);
        if ($result){
            return CommonService::success([],106);
        } else {
            return CommonService::error(0);
        }
    }

    /**
     *设置提现密码
     * @param Request $request
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function withdrawPasswordAdd(Request $request)
    {
        $partnerId = $request->partnerId;
        $requestData = request()->post();
        $validate = Validate::make([
            'w_password|提现密码' => 'require',
            'w_password1|重复提现密码' => 'require',
        ]);
        if (!$validate->check($requestData)){
            return CommonService::error($validate->getError());
        }
        $partnerInfo = Db::name('partner')->where('id', $partnerId)->find();
        if (!$partnerInfo){
            return CommonService::error(1);
        }
        if ($requestData['w_password'] != $requestData['w_password1']){
            return CommonService::error(105);
        }
        $result = Db::name('partner')->where('id', $partnerId)->update([
            'withdraw_password' => $requestData['w_password'],
        ]);
        if ($result){
            return CommonService::success([],107);
        } else {
            return CommonService::error(0);
        }
    }

    /**
     *合伙状态
     * @param Request $request
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function getPartnerState(Request $request)
    {
        $partnerId = $request->partnerId;
        $partnerInfo = Db::name('partner')->where('id',$partnerId)->field('super_partner_id,rebate_percent,reg_time')->find();
        if (!$partnerInfo){
            return CommonService::error(1);
        }
        $superPartnerInfo = Db::name('user_manage')
            ->alias('u')
            ->leftJoin('super_partner s','s.uid = u.id')
            ->where('s.id',$partnerInfo['super_partner_id'])
            ->field('u.xingming,u.tel')
            ->find();
        $data = array_merge($partnerInfo,$superPartnerInfo);
        return CommonService::success($data);
    }

    /**
     *发送验证码
     * @param Request $request
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function getTelSms(Request $request)
    {
        $partnerId = $request->partnerId;
        $requestData = request()->post();
        $validate = Validate::make([
            'tel|手机号' => 'require|mobile',
        ]);
        if (!$validate->check($requestData)) {
            return CommonService::error($validate->getError());
        }
        $partner = Db::name('partner')->where('id', $partnerId)->find();
        if (!$partner){
            return CommonService::error(1);
        }
//        if (!empty($smsCodeTelTime)){
//            return CommonService::error('请勿在60秒内重复发送验证码！');
//        }
        $templateParam['code'] = mt_rand(1000, 9999);
        $send = CommonService::sendSms($requestData['tel'], $templateParam, 'SMS_175535973');
        if ($send) {
            if (Cache::get('sendSmsCount' . $requestData['tel']) <= 0) {
                $time = strtotime(date('Y-m-d')) + 86400 - time();
                Cache::set('sendSmsCount' . $requestData['tel'], 1, $time);
            } else {
                Cache::inc('sendSmsCount' . $requestData['tel'], 1);
            }
            Cache::set('smsCode' . $requestData['tel'], $templateParam['code'], 300);
//            Cache::set('smsCodeTelTime' . $requestData['tel'], time(), 60);
            return CommonService::success([], '验证码已发送！');
        } else {
            return CommonService::error(3);
        }
    }

}